﻿using Chire.ChireInter.Teacher;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Chire.ChireInter.Students;

namespace Chire.ChireInter.Login
{
    public class Login_Action
    {
        public enum LoginType
        {
            loginType_phone = 0,                // 手机登录
            loginType_wechat = 1,               // 微信登录
            loginType_qq = 2,                   // qq登录
            loginType_SmallProduct = 3,         // 微信小程序登陆a
        }

        public enum User_Status
        {
            user_status_normal = 0,             // 表示正常用户
            user_status_shenhe = 1,             // 审核中
        }


        #region 进行用户登录
        public User_Model mainLoginManager(User_Type userType, string nick, int gender, string birthday, string phone, LoginType loginType, string unionid,string open_id,string avatar) {
            User_Model userModel = new User_Model();
            // 1. 获取openId
            bool hasUser = hasUserWithOpenId(open_id);
            // 判断
            if (hasUser == false) {   // 表示没有，就创建
                userModel = registerUserManager(userType, nick, gender, birthday, phone, loginType, "", unionid, avatar, 0,open_id);
            }
            else {
                userModel = getUserInfoManagerWithOpenId(open_id);
            }

            return userModel;
        }
        #endregion


        #region 老师登陆
        public User_Model thirdLoginmanager(User_Type userType, string nick, int gender, string birthday, string phone, LoginType loginType, string device, string union_id, string avatar, int money)
        {
            string userUnion = "";
            if (loginType == LoginType.loginType_phone)
            {
                userUnion = phone;
            } else {
                userUnion = union_id;
            }

            // 判断该账号是否存在
            User_Model userModel = teacherHasInServer(loginType, userUnion);
            if (userModel.id != null)
            {
                return userModel;
            }
            else {
                userModel = registerUserManager(userType, nick, gender, birthday, phone, loginType, device, union_id, avatar, money, "");
                return userModel;
            }
        }

       
        #endregion

        #region 判断是否有老师存在
        private User_Model teacherHasInServer(LoginType login_type, string unionId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "";
            if (login_type ==  LoginType.loginType_phone)
            {
                strselect = "select * from user_list where phone = '" + unionId + "'";
            }
            else if (login_type == LoginType.loginType_qq || login_type == LoginType.loginType_wechat)
            {
                int type = (int)login_type;
                strselect = "select * from user_list where union_id = '" + unionId + "' and login_type = " + type + "";
            }

            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();

            if (dr.Read())
            {
                userModel.id = dr["userId"].ToString();                              // 用户id
                userModel.avatar = dr["avatar"].ToString();                          // 头像
                userModel.nick = dr["nick"].ToString();                              // 昵称
                userModel.phone = dr["phone"].ToString();                            // 支付宝
                userModel.sex = Convert.ToInt32(dr["sex"].ToString());               // 性别
                userModel.birthday = dr["birthday"].ToString();                      // 年龄
                userModel.login_type = Convert.ToInt32(dr["login_type"].ToString()); // 登录类型
                userModel.device = dr["device"].ToString();                          // 设备号
                userModel.union_id = dr["union_id"].ToString();                      // qq登录的唯一号
                userModel.open_id = dr["open_id"].ToString();
                userModel.money = Convert.ToInt32(dr["money"].ToString());           // 钱
                userModel.im_id = dr["im_id"].ToString();                            // IMID
                userModel.zhifupay = dr["zhifupay"].ToString();                      // 支付宝
                userModel.user_type = (User_Type)Convert.ToInt32(dr["user_type"].ToString());

                Teacher_Action teacherAction = new Teacher_Action();
                Teacher_Model teacherModel = teacherAction.getTeacherWithId(userModel.id);
                
                userModel.teacher = teacherModel;
            }
          
            sqlcon.Close();
            return userModel;
        }
        #endregion

        #region 注册账号
        public User_Model registerUserManager(User_Type userType, string nick, int gender, string birthday, string phone, LoginType login_type, string device, string union_id, string avatar, int money,string open_id)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";

            StrInsert = "insert into user_list(userId,avatar,nick,sex,birthday,phone,login_type,device,union_id,money,createtime,im_id,zhifupay,user_type,open_id) values(@userId,@avatar,@nick,@sex,@birthday,@phone,@login_type,@device,@union_id,@money,@createtime,@im_id,@zhifupay,@user_type,@open_id)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            User_Model userModel = new User_Model();
            // 用户id
            cmd.Parameters.Add("@userId", SqlDbType.NVarChar);
            cmd.Parameters["@userId"].Value = open_id;
            userModel.id = open_id;

            cmd.Parameters.Add("@im_id", SqlDbType.NVarChar);
            cmd.Parameters["@im_id"].Value = open_id;
            userModel.id = open_id;

            // 昵称
            cmd.Parameters.Add("@nick", SqlDbType.NVarChar);
            cmd.Parameters["@nick"].Value = nick;
            userModel.nick = nick;
            // 性别
            cmd.Parameters.Add("@sex", SqlDbType.Int);
            cmd.Parameters["@sex"].Value = gender;
            userModel.sex = gender;
            // 年龄
            cmd.Parameters.Add("@birthday", SqlDbType.NVarChar);
            cmd.Parameters["@birthday"].Value = birthday;
            userModel.birthday = birthday;
            // 手机号
            cmd.Parameters.Add("@phone", SqlDbType.NVarChar);
            cmd.Parameters["@phone"].Value = phone;
            userModel.phone = phone;
            // 登录类型
            cmd.Parameters.Add("@login_type", SqlDbType.Int);
            cmd.Parameters["@login_type"].Value = login_type;
            userModel.login_type = (int)login_type;
            // 设备号
            cmd.Parameters.Add("@device", SqlDbType.NVarChar);
            cmd.Parameters["@device"].Value = device;
            userModel.device = device;
            // 唯一号
            cmd.Parameters.Add("@union_id", SqlDbType.NVarChar);
            cmd.Parameters["@union_id"].Value = union_id;
            userModel.union_id = union_id;
            // open号
            cmd.Parameters.Add("@open_id", SqlDbType.NVarChar);
            cmd.Parameters["@open_id"].Value = open_id;
            userModel.open_id = open_id;

            // 头像
            cmd.Parameters.Add("@avatar", SqlDbType.NVarChar);
            cmd.Parameters["@avatar"].Value = avatar;
            userModel.avatar = avatar;

            cmd.Parameters.Add("@money", SqlDbType.Int);
            cmd.Parameters["@money"].Value = money;
            userModel.money = money;

            cmd.Parameters.Add("@zhifupay", SqlDbType.NVarChar);
            cmd.Parameters["@zhifupay"].Value = "";
            userModel.zhifupay = "";

            // 时间
            cmd.Parameters.Add("@createtime", SqlDbType.VarChar, 50);
            cmd.Parameters["@createtime"].Value = DateTime.Now.ToString();
            // 用户类型
            cmd.Parameters.Add("@user_type", SqlDbType.Int);
            cmd.Parameters["@user_type"].Value = (int)User_Type.User_TypeNormal;


            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
            return userModel;
        }
        #endregion

        #region 用户id生成规则
        public string createUserId()
        {
            DateTime dt = DateTime.Now;
            string str = dt.ToString("yyyyMMddHHmmss");
            string order = getRandomStr(5) + str + getRandomStr(7);
            string newOrder = md5(order);
            return newOrder;
        }

        public string md5(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();

        }

        private string SHA256Encrypt(string str)
        {
            System.Security.Cryptography.SHA256 s256 = new System.Security.Cryptography.SHA256Managed();
            byte[] byte1;
            byte1 = s256.ComputeHash(Encoding.Default.GetBytes(str));
            s256.Clear();
            return Convert.ToBase64String(byte1);
        }

        public string getRandomStr(int n)//b：是否有复杂字符，n：生成的字符串长度
        {
            string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            StringBuilder SB = new StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < n; i++)
            {
                SB.Append(str.Substring(rd.Next(0, str.Length), 1));
            }
            return SB.ToString();
        }
        #endregion

        #region 生成4位随机数
        public string getFourRandomNumber()
        {
            string randomNum = getFourRandomNumberManager();
            bool has = false;
            while (has == false)
            {
                randomNum = getFourRandomNumberManager();
                has = unionIdHasIn(randomNum);
            }

            return randomNum;
        }

        private string getFourRandomNumberManager()
        {
            string str = "0123456789";

            StringBuilder SB = new StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < 1; i++)
            {
                SB.Append(str.Substring(rd.Next(0, str.Length), 1));
            }
            return SB.ToString();
        }

        private bool unionIdHasIn(string numberId)
        {
            // 连接数据库

            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "select * from user_list where userId = '" + numberId + "'";

            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();
            bool has = true;
            if (dr.Read())
            {
                has = false;
            }
            else
            {            // 表示没有这个账号，去注册
                has = true;
            }
            sqlcon.Close();
            return has;
        }
        #endregion

        #region 根据用户id 获取信息
        public User_Model getUserInfoManagerWithId(string userId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "select * from user_list where userId = '" + userId + "'";
          
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();

            if (dr.Read())
            {
                userModel.id = dr["userId"].ToString();                              // 用户id
                userModel.avatar = dr["avatar"].ToString();                          // 头像
                userModel.nick = dr["nick"].ToString();                              // 昵称
                userModel.phone = dr["phone"].ToString();                            // 支付宝
                userModel.sex = Convert.ToInt32(dr["sex"].ToString());               // 性别
                userModel.birthday = dr["birthday"].ToString();                      // 年龄
                userModel.login_type = Convert.ToInt32(dr["login_type"].ToString()); // 登录类型
                userModel.device = dr["device"].ToString();                          // 设备号
                userModel.union_id = dr["union_id"].ToString();                      // qq登录的唯一号
              
                userModel.money = Convert.ToInt32(dr["money"].ToString());           // 钱
                userModel.im_id = dr["im_id"].ToString();                                // IMID
                userModel.zhifupay = dr["zhifupay"].ToString();                          // 支付宝
                userModel.user_type = (User_Type)Convert.ToInt32(dr["user_type"].ToString());

                // 根据老师信息
                Teacher_Action teacherAction = new Teacher_Action();

                Teacher_Model teacherModel = teacherAction.getTeacherWithId(userId);
                userModel.teacher = teacherModel;
            }

            sqlcon.Close();
            return userModel;
    
        }
        
        #endregion

        #region 修改用户信息
        public void updateUserInfo(string userId, string key, string value)
        {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update user_list set " + key + " = '" + value + "'  where userId ='" + userId + "'";


            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
        }

        public void updateUserInfoWithopenId(string openId, string key, string value)
        {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update user_list set " + key + " = '" + value + "'  where open_id ='" + openId + "'";


            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
        }

        #endregion

        #region 根据openId判断是否有用户存在
        private bool hasUserWithOpenId(string openId){
            bool hasUse = false;

              // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "";
            strselect = "select * from user_list where open_id = '" + openId + "'";
           

            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();

            if (dr.Read())
            {
                hasUse = true;
            }
          
            sqlcon.Close();
            return hasUse;
        }
        #endregion

        #region 根据用户id 获取信息
        public User_Model getUserInfoManagerWithOpenId(string openId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "select * from user_list where open_id = '" + openId + "'";

            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();

            if (dr.Read())
            {
                userModel.id = dr["userId"].ToString();                              // 用户id
                userModel.avatar = dr["avatar"].ToString();                          // 头像
                userModel.nick = dr["nick"].ToString();                              // 昵称
                userModel.phone = dr["phone"].ToString();                            // 支付宝
                userModel.sex = Convert.ToInt32(dr["sex"].ToString());               // 性别
                userModel.birthday = dr["birthday"].ToString();                      // 年龄
                userModel.login_type = Convert.ToInt32(dr["login_type"].ToString()); // 登录类型
                userModel.device = dr["device"].ToString();                          // 设备号
                userModel.union_id = dr["union_id"].ToString();                      // qq登录的唯一号
                userModel.open_id = dr["open_id"].ToString();                      // qq登录的唯一号

                userModel.money = Convert.ToInt32(dr["money"].ToString());           // 钱
                userModel.im_id = dr["im_id"].ToString();                                // IMID
                userModel.zhifupay = dr["zhifupay"].ToString();                          // 支付宝
                userModel.user_type = (User_Type)Convert.ToInt32(dr["user_type"].ToString());


                if (userModel.user_type == User_Type.User_TypeNormal)
                {

                }
                else if (userModel.user_type == User_Type.User_TypeTeacher)
                {
                    // 根据老师信息
                    Teacher_Action teacherAction = new Teacher_Action();

                    Teacher_Model teacherModel = teacherAction.getTeacherWithId(userModel.id);
                    userModel.teacher = teacherModel;
                }
                else if (userModel.user_type == User_Type.User_TypeStudent)
                {
                    Student_Action studentAction = new Student_Action();
                    Student_Model studentModel = studentAction.getStudentInfoWithStudentOpenId(userModel.open_id);
                    userModel.studentInfo = studentModel;
                }
                else if (userModel.user_type == User_Type.User_TypeParent)
                {

                }
                else if (userModel.user_type == User_Type.User_TypeAdmin)
                { 
                
                }

               
            }

            sqlcon.Close();
            return userModel;

        }

        #endregion

        #region 根据openid 判断是否是管理员
        public bool hasAdminManager(string openid) {
            bool hasAdmin = false;

            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string strselect = "";
            strselect = "select * from user_list where open_id = '" + openid + "' and user_type = '"+4+"'";


            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            User_Model userModel = new User_Model();

            if (dr.Read())
            {
                hasAdmin = true;
            }

            sqlcon.Close();
            return hasAdmin;
        }
        #endregion

    }
}